package adminRole

import (
	"grpc.getaway.adminspro.padmins.com/internal/api/module/admin/container"
	"grpc.getaway.adminspro.padmins.com/internal/api/utils/rpc"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
	"strconv"
	"strings"
)

func Add(c *container.Context) (interface{}, error) {

	status, _ := strconv.ParseInt(c.Request.ParamsToString("status", "1"), 10, 32)
	pid, _ := strconv.ParseInt(c.Request.ParamsToString("pid", "0"), 10, 64)
	req := &pbAdmin.AdminRoleAddReq{
		OperaterId: c.Auth.Data.Admin.Id,
		AdminRole: &pbAdmin.AdminRole{
			Pid:    pid,
			Name:   c.Request.ParamsToString("name"),
			Status: int32(status),
		},
		ResourceId: []int64{},
	}

	resource_id := strings.Split(c.Request.ParamsToString("resource_id", ""), ",")
	req.ResourceId = make([]int64, len(resource_id))
	for i, resourceId := range resource_id {
		if rid, e := strconv.ParseInt(resourceId, 10, 64); e == nil {
			req.ResourceId[i] = rid
		}
	}

	resp, e := rpc.GetAdminClient().AdminRoleAdd(c.GetContext(), req)

	if e != nil {
		return resp, e
	}

	return map[string]map[string]interface{}{
		"row": {"id": resp.Id},
	}, nil
}
